<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Wechat;
use app\common\model\Category;
use app\common\model\User;
use fast\Http;
use think\Db;

/**
 * 申请入驻管理
 *
 * @icon fa fa-circle-o
 */
class Enter extends Backend
{

    /**
     * Enter模型对象
     * @var \app\common\model\user\Enter
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\user\Enter;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("stateList", $this->model->getStateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname']);
                $cate = Category::whereIn('id', $row->category_ids)->column('nickname');
                $row->cate_text = implode(',', array_values($cate));
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 审核
     */
    public function examine($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $user = User::get($row->user_id);
                $row->state = 1;
                $res = $row->save();
                if (!$res) {
                    exception('审核失败');
                }
                if ($row->type == 1) {
                    $user->employee = 4;
                }
                if ($row->type == 2) {
                    if ($user->partner == 3) {
                        exception('用户已是合作商');
                    }
                    $user->salesman = 2;
                }
                if ($row->type == 3) {
                    if ($user->salesman == 2) {
                        exception('用户已是业务员');
                    }
                    $user->partner = 3;
                }
                if ($row->type != 1) {
                    $wechat = new Wechat('wxMiniProgram');
                    $decrypt = $wechat->getAccessToken();
                    $token = $decrypt['access_token'];
                    $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$token";
                    $qr_code = generate_invite_code();
                    $data = json_encode([
                        'path' => 'pages/index/index?qr_code=' . $qr_code,
                    ]);
                    $user->qr_code = $qr_code;
                    $http = new Http;
                    $response = $http->post($url, $data);
                    $res = json_decode($response, true);
                    if (!is_array($res)) {
                        $file = self::saveTempImageByContent($response);
                        if (!file_exists($file)) {
                            exception('二维码保存失败:' . $file);
                        }
                        $user->qr_image = '/' . $file;
                    } else {
                        exception('失败:' . $res['errmsg']);
                    }
                }
                $user->save();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('审核成功');
        }
    }
    static function qrImage($content)
    {
    }
    static function saveTempImageByContent($content)
    {
        $dir1 = ROOT_PATH . 'public/uploads/wx_qrcode/';
        if (!is_dir($dir1)) @mkdir($dir1, 0777);
        $save_name = md5(base64_encode($content)) . '.jpg';
        $save_path = 'uploads/wx_qrcode/' . $save_name;
        $fp = fopen($dir1 . $save_name, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }
}
